package com.autumn.search.elasticsearch.plugin;

import java.io.IOException;
import java.util.Map;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;

/**
 * 索引处理器
 * 
 * @author 老码农
 *         <p>
 *         Description
 *         </p>
 * @date 2018-02-04 16:34:54
 */
public class AutumnIndexRestHandler extends BaseRestHandler {

	protected AutumnIndexRestHandler(Settings settings, RestController restController) {
		super(settings);
		restController.registerHandler(RestRequest.Method.POST, "/autumn", this);
		restController.registerHandler(RestRequest.Method.GET, "/autumn", this);
	}

	@Override
	public String getName() {
		return "autumn_index_handler";
	}

	@Override
	protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
		Map<String, String> params = request.params();
		// channel:org.elasticsearch.rest.RestController ass;

		return channel -> execute(client, params, channel);
	}

	private void execute(Client client, Map<String, String> params, RestChannel channel) {
		if (channel == null) {
			this.logger.info("autumn 请求的 channel 为 null");
		} else {
			this.logger.info("autumn 请求来了 channel:" + channel.getClass().getName());
		}
		String json = "{\"a\":1,\"b\":6}";
		BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, json);
		channel.sendResponse(bytesRestResponse);
	}

}
